package com.manshutingyu.system.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.manshutingyu.common.core.constants.CommonConstant;
import com.manshutingyu.common.core.dto.LoginUserDTO;
import com.manshutingyu.common.core.dto.R;
import com.manshutingyu.system.domain.SysUser;
import com.manshutingyu.system.mapper.SysMenuMapper;
import com.manshutingyu.system.mapper.SysUserMapper;
import com.manshutingyu.system.mapper.SysUserRoleMapper;
import com.manshutingyu.system.service.SysUserService;
import jakarta.annotation.Resource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @Author：yinyuxia
 * @Date：2025/3/29 16:44
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();
  @Resource
  private SysUserMapper sysUserMapper;
  @Resource
  private SysUserRoleMapper userRoleMapper;
  @Resource
  private SysMenuMapper sysMenuMapper;
    @Override
    public IPage<SysUser> getPage(Page<SysUser> page, SysUser sysUser) {

        return null;
    }

    @Override
    public SysUser getUserById(Long id) {
        SysUser user = getById(id);

        return user;
    }

    @Override
    public Boolean createUser(SysUser user) {
        if (this.getDbUser(user)) {
            return false;
        }
        boolean result = save(user);
        return result;
    }

    @Override
    public Boolean updateUser(SysUser user) {
        if (getDbUser(user)) {
            return false;
        }

        // 更新用户
        return updateById(user);
    }

    @Override
    public Boolean deleteByIds(Long[] ids) {

        return removeByIds(Arrays.asList(ids));
    }

    @Override
    public Boolean updatePasswordByUserId(Long userId, String password) {
      //  removeCache(userId);
        // 新密码
        String newPass = ENCODER.encode(password);
        return update(Wrappers.<SysUser>lambdaUpdate()
                .set(SysUser::getPassword, newPass)
                .eq(SysUser::getId, userId));
    }

    @Override
    public R<LoginUserDTO> selectByUsername(String userName) {
        SysUser sysUser=  sysUserMapper.selectByUsername(userName);
        if (sysUser==null){
            return R.error("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = userRoleMapper.getRoleListByUserId(sysUser.getId());
        // 权限集合
        Set<String> permissions = new HashSet<>();
        // 如果 roles 包含 root 则拥有所有权限
        if (roles.contains(CommonConstant.SUPER_ADMIN_ROOT)) {
            permissions.add(CommonConstant.ALL_PERMISSION);
        } else {
            // 获取菜单权限标识
            permissions = sysMenuMapper.getMenuPermission(sysUser.getId());
            // 过滤空字符串
            permissions.remove("");
        }
        LoginUserDTO loginUserDTO= BeanUtil.copyProperties(sysUser, LoginUserDTO.class);
        loginUserDTO.setRoles(roles);
        loginUserDTO.setPermissions(permissions);
        return R.success(loginUserDTO);
    }

    private Boolean getDbUser(SysUser user) {
        String password = user.getPassword();
        SysUser dbUser = getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUserName, user.getUserName()));
        if (dbUser != null && !Objects.equals(dbUser.getId(), user.getId())) {
            return true;
        }

        return false;
    }


}
